<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>计算器</title>
    <style>
        input {
            display: block;
            width: 50%;
            text-align: center;
            height: 30px;
            margin: 0.5pc auto;
            outline: none;
        }

        table {
            display: table;
            border-collapse: collapse !important;
            width: 60%;
            margin: 1pc auto;
            text-align: center;
        }

        th, td {
            border: #222222 1px solid;
            display: table-cell;
        }
    </style>
</head>
<body>
<h2 style="text-align: center">一元函数计算器</h2>
<input placeholder="自变量（多个自变量用“,”隔开，例：“1,2,3,4,5”）" id="variable">
<input placeholder="函数（变量使用“x”引入，例：“2*sin(x+2)+3*cos(x+5)+x”）" id="pro">
<input type="button" onclick="cal()" value="计算" style="width: 20%">
<table>
    <thead>
    <tr>
        <th>自变量</th>
        <th>函数</th>
        <th>结果</th>
    </tr>
    </thead>
    <tbody id="tbody"></tbody>
</table>
<h3>函数参考</h3>
<ul>
    <li>幂运算：pow(底数，指数)，例：x+5的8次方——pow(x,8)</li>
    <li>自然对数：log()，例：x+5的自然对数——log(x+5)</li>
    <li>绝对值：abs()，例：x+5的绝对值——abs(x+5)</li>
    <li>保留小数位：().rev()，例，x+5保留8位小数——(x+5).rev(8)</li>
</ul>
<script type="text/javascript" src="http://cdn.lifanko.cn/tip10.min.js"></script>
<script>
    function cal() {
        var table = '';
        var variable = document.getElementById('variable').value;
        if (variable === '') {
            tip("请输入自变量", "22%", 2000, "1", false);
        } else {
            if (variable.length > 0) {
                variable = variable.replace(/，/g, ',');
                variable = variable.split(',');
            }
            var pro = document.getElementById('pro').value;
            pro = pro.replace(/cos/g, 'Math.cos');
            pro = pro.replace(/sin/g, 'Math.sin');
            pro = pro.replace(/tan/g, 'Math.tan');
            pro = pro.replace(/pow/g, 'Math.pow');
            pro = pro.replace(/log/g, 'Math.log');
            pro = pro.replace(/abs/g, 'Math.abs');

            for (var i = 0; i < variable.length; i++) {
                var pro_buffer = pro.replace(/x/g, variable[i]);
                pro_buffer = pro_buffer.replace(/rev/g, 'toFixed');

                try {
                    var result = eval(pro_buffer);
                    table = table + "<tr><td>" + variable[i] + "</td><td>" + pro_buffer + "</td><td>" + result + "</td></tr>";
                } catch (err) {
                    tip("无法完成计算", "22%", 2000, "1", false);
                }
            }
            if (table !== '') {
                document.getElementById('tbody').innerHTML = table;
            }
        }
    }
</script>
</body>
</html>